import 'dart:io';

import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

class FileOperationDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new FileOperationRoute();
  }
}

class FileOperationRoute extends StatefulWidget {
  FileOperationRoute({Key key}) : super(key: key);

  @override
  _FileOperationRoute createState() => new _FileOperationRoute();
}

class _FileOperationRoute extends State<FileOperationRoute> {
  int _counter;

  @override
  void initState() {
    super.initState();
    //从文件中读取次数
    _readCounter().then((int value) {
      setState(() {
        _counter = value;
      });
    });
  }

  //创建储存目录
  Future<File> _getLocalFile() async {
    //获取应用目录
    String dir = (await getApplicationDocumentsDirectory()).path;
    return new File('$dir/counter.txt');
  }

  //读取文件
  Future<int> _readCounter() async {
    try {
      File file = await _getLocalFile();
      //读取点击次数（已字符串形式）
      String contents = await file.readAsString();
      return int.parse(contents);
    } on FileSystemException {
      return 0;
    }
  }

  //写入文件
  Future<Null> _incrementCounter() async {
    setState(() {
      _counter++;
    });
    await (await _getLocalFile()).writeAsString("$_counter");
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(title: new Text("文件操作")),
      body: new Center(
        child: new Text("点击了$_counter 次"),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ),
    );
  }
}
